package com.cyh.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

public class DatagramChannelDemo3 {

    public static void main(String[] args) throws IOException, InterruptedException {

        DatagramChannel connChannel = DatagramChannel.open();
        //绑定
        connChannel.bind(new InetSocketAddress(9999));

        //连接
        connChannel.connect(new InetSocketAddress("127.0.0.1", 9999));

        connChannel.write(ByteBuffer.wrap("发送我们的数据".getBytes("UTF-8")));

        ByteBuffer readBuffer = ByteBuffer.allocate(1024);


        //接收
        while(true){
            readBuffer.clear();
            connChannel.receive(readBuffer);
            readBuffer.flip();
            System.out.println(Charset.forName("UTF-8").decode(readBuffer));
            
        }
    }
}
